package com.atxiaodei.kabudaspringannotation.demo.annotaions.configures.gupaoannotion;

import com.atxiaodei.kabudaspringannotation.project.annotion.GupaoAnnotionClass;
import com.atxiaodei.kabudaspringannotation.project.annotion.GupaoAnnotionMethod;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by kabuda
 */
@Component
public class GupaoBeanPostProcessor implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Object instance = null;
        if(bean.getClass().isAnnotationPresent(GupaoAnnotionClass.class)){
            GupaoAnnotionClass annotation = bean.getClass().getAnnotation(GupaoAnnotionClass.class);
            if(annotation.value()){
                return bean;
            }
            Method[] declaredMethods = bean.getClass().getDeclaredMethods();
            for(Method method : declaredMethods){
                if(method.isAnnotationPresent(GupaoAnnotionMethod.class)) {
                    GupaoAnnotionMethod annotionMethod = method.getAnnotation(GupaoAnnotionMethod.class);
                    if("huihui".equals(annotionMethod.value())){
                        instance = getInstance(bean.getClass());
                    }
                }
            }
        }
        return instance;
    }

    public Object getInstance(Class<?> clazz) throws BeansException {
        //相当于Proxy，代理的工具类
        // 生成的代码是代理类的子类
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(clazz);
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
                System.out.println("准备开始学习");
                Object obj = methodProxy.invokeSuper(o,objects);
                System.out.println("一天就学会了");
                return obj;
            }
        });
        return enhancer.create();
    }
}
